# https://support.huaweicloud.com/bestpractice-iam/iam_0508.html
# Tenant ID: hw85695042

# --------
# IAM User
resource "huaweicloud_identity_user" "student" {
  count = var.student_count

  name        = "${var.project_name}-iam-user-${count.index}"
  description = "SXZ ZMM User"
  password    = var.student_password
}

resource "huaweicloud_identity_access_key" "student" {
  count = var.student_count

  user_id = huaweicloud_identity_user.student[count.index].id
  secret_file  = "/tmp/student_user_aksk/${count.index}.csv"
}


# --------------
# IAM User Group
resource "huaweicloud_identity_group" "student" {
  name        = "${var.project_name}-iam-group"
  description = "SXZ ZMM User Group"
}


resource "huaweicloud_identity_group_membership" "student_role_membership" {
  group = huaweicloud_identity_group.student.id
  users = huaweicloud_identity_user.student.*.id
}


# -------------------
# IAM User Group Role
resource "huaweicloud_identity_role" student {
  name        = "student"
  description = "Student role"
  type        = "AX"
  policy      = <<EOF
{
    "Version": "1.1",
    "Statement": [
        {
            "Action": [
                "cci:rbac:get",
                "cci:rbac:list",
                "cci:namespace:get",
                "cci:namespace:list",
                "cci:namespace:create",
                "cci:namespace:delete",
                "cci:network:get",
                "cci:network:create",
                "cci:network:delete",
                "cci:network:list",
                "cci:namespaceSubResource:*",
                "cci:addonTemplate:*",
                "cci:addonInstance:*",

                "vpc:*:get",
                "vpc:*:list",

                "obs:bucket:ListAllMybuckets",
                "obs:bucket:HeadBucket",
                "obs:bucket:ListBucket",
                "obs:bucket:GetBucketLocation",
                "SWR:software:*",
                "SWR:dockerimage:*",

                "elb:*:get",
                "elb:*:list",
                "evs:*:get",
                "evs:*:list",
                "aom:*:get",
                "aom:*:list",
                "apm:*:get",
                "apm:*:list",
                "nat:*:get",
                "nat:*:list",
                "kms:cmk:list",
                "kms:cmk:get",
                "swr:*:list",
                "swr:*:get"
            ],
            "Effect": "Allow"
        }
    ]
}
EOF
}


# ------------------------------
# IAM User Group Role Assignment
resource "huaweicloud_identity_role_assignment" "student_role_assignment" {
  role_id    = huaweicloud_identity_role.student.id
  group_id   = huaweicloud_identity_group.student.id
  project_id = "06b1feea1a8010552fa6c006e51c302c"  # ShangHai 2 region
}
